package com.moon.back.config;


import com.alibaba.ttl.threadpool.TtlExecutors;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * async 异步方法所使用的线程池
 *
 * @author zhanggengyong
 */

@EnableAsync(proxyTargetClass = true)
@Configuration
public class MoonExecutorConfig implements AsyncConfigurer {
    /**
     * CPU 核心数
     */
    private final int N_CPU = Runtime.getRuntime().availableProcessors();

    private final int CORE_POOL_SIZE = 2 * N_CPU;

    private final int MAX_POOL_SIZE = 2 * N_CPU;

    private static final int QUEUE_CAPACITY = 100;

    private static final int KEEP_ALIVE_TIME = 60;

    public static final String EXECUTOR_NAME = "moon_async_executor";

    public static final String THREAD_NAME_PREFIX = EXECUTOR_NAME + "#task-";


    @Bean(EXECUTOR_NAME)
    public Executor moonAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程池大小
        executor.setCorePoolSize(CORE_POOL_SIZE);
        // 最大线程数
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        // 队列容量
        executor.setQueueCapacity(QUEUE_CAPACITY);
        // 活跃时间
        executor.setKeepAliveSeconds(KEEP_ALIVE_TIME);
        // 线程名字前缀
        executor.setThreadNamePrefix(THREAD_NAME_PREFIX);

        // setRejectedExecutionHandler：当pool已经达到max size的时候，如何处理新任务
        // CallerRunsPolicy：不在新线程中执行任务，而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return TtlExecutors.getTtlExecutor(executor);
//        return null;
    }


    @Override
    public Executor getAsyncExecutor() {
        return moonAsyncExecutor();
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return AsyncConfigurer.super.getAsyncUncaughtExceptionHandler();
    }
}
